package com.example.platform.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.platform.web.config.AesSecurityUtil;
import com.example.platform.web.config.ResultInfo;
import com.example.platform.web.config.Status;
import com.example.platform.web.entity.SysUser;
import com.example.platform.web.entity.SysUserVo;
import com.example.platform.web.mapper.SysUserMapper;
import com.example.platform.web.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Override
    public int insertModel(SysUser user) {
        user.setPassword(AesSecurityUtil.entryptPassword(user.getPassword()));
        user.setCreateDate(new Date());
        user.setDelFlag("0");
        return sysUserMapper.insert(user);
    }

    @Override
    public int deleteByModel(SysUser user) {

        user.setUpdateDate(new Date());
        user.setDelFlag("1");
        return sysUserMapper.updateById(user);
    }

    @Override
    public int update(SysUser user) {
        user.setDelFlag("0");
        user.setUpdateDate(new Date());
        return sysUserMapper.updateById(user);
    }

    @Override
    public SysUser findByModel(SysUser user) {
        return sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery(user));
    }

    @Override
    public ResultInfo login(SysUser user) {

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserAccount,user.getUserAccount());
        SysUser sysUser=sysUserMapper.selectOne(queryWrapper);
        boolean password=AesSecurityUtil.validatePassword(user.getPassword(),sysUser.getPassword());
        if(password){
            ResultInfo resultInfo=new ResultInfo(Status.SUCCESS);

            return resultInfo;
        }


        return new ResultInfo(Status.WARN.code,"账户或者密码错误");
    }

    @Override
    public IPage<SysUser> selectByPage(SysUserVo sysUserVo) {
        IPage<SysUser> iPage = new Page<>(Integer.valueOf(sysUserVo.getPageNum()),Integer.valueOf(sysUserVo.getPageSize()));
        SysUser user=new SysUser();
        BeanUtils.copyProperties(sysUserVo,user);
        return sysUserMapper.selectPage(iPage,Wrappers.<SysUser>lambdaQuery(user));
    }
}
